<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.isReg" clearable style="width: 160px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="listQuery.userNickName" placeholder="昵称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.userName" placeholder="真实姓名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.userPhone" placeholder="手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button v-permission="['管理员','超级管理员']" v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{ $t('table.export') }}</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="编号" type="index" align="center" width="60" />
      <el-table-column label="昵称" prop="userNickName" align="center" />
      <el-table-column label="真实姓名" prop="userName" align="center" />
      <el-table-column :formatter="formatSex" label="性别" prop="userSex" align="center" width="80" />
      <el-table-column label="来源" prop="promotion_id" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.promotion_id?'推荐':'-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="userPhone" align="center" />
      <el-table-column label="生日" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.userBirthday }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在地" prop="userDomicile" align="center" />
      <el-table-column label="注册时间" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :formatter="formatStatus" prop="rdd_user_statuses" label="用户状态" align="center" />
      <el-table-column label="所属公司" prop="affiliatedCompany" align="center" />
      <el-table-column label="所属直营店" prop="promotion_id" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.rdd_store&&scope.row.rdd_store.storeName?scope.row.rdd_store.storeName:'-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280">
        <template slot-scope="scope">
        	<el-button v-show='scope.row.rdd_user_statuses.length>0' v-permission="['直营店', '加盟店', '超级管理员','管理员','财务人员']" type="primary" size="mini" @click="handleUserDataInput(scope.row)">用户数据</el-button>
          <el-button v-permission="['直营店']" v-show="scope.row.rdd_user_statuses.length>0 && scope.row.rdd_user_statuses[0].userStatus==1 && scope.row.userPhone" type="primary" size="mini" @click="handleDistributeFactory(scope.row)">分配到厂</el-button>
          <el-button v-permission="['经纪人']" v-show="scope.row.rdd_user_statuses.length>0 && scope.row.rdd_user_statuses[0].userStatus==0" type="primary" size="mini" @click="handleDistribute(scope.row)">分配到店</el-button>
          <el-button v-permission="['经纪人']" v-show="scope.row.rdd_user_statuses.length>0 && scope.row.rdd_user_statuses[0].userStatus==2" type="primary" size="mini" @click="handleDistributeConfirm(scope.row)">审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <el-dialog :visible.sync="innerVisible" title="分配到店" append-to-body width="30%">
      <el-form ref="dataForm2" label-position="right" label-width="100px">
        <el-form-item label="选择直营店">
          <el-select v-model="temp.store_id" style="width: 160px" class="filter-item">
            <el-option v-for="item in stores" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="distributeShop">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="innerVisible2" title="审核" append-to-body width="30%">
      <div>确认通过审核吗？</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible2 = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="distributeShopConfirm">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="innerVisible3" title="分配到厂" append-to-body width="30%">
      <el-form ref="dataForm3" label-position="right" label-width="100px">
        <el-form-item label="选择公司">
          <el-select filterable v-model="temp3.company_id" style="width: 200px" class="filter-item">
            <el-option v-for="item in enterpriseOptions" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible3 = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="distributeFactory">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="innerVisible4" title="用户数据" append-to-body width="50%">
      <el-form ref="dataForm4" :model="temp4" label-position="right" label-width="150px" style="width: 500px; margin-left:50px;" :rules="rules">
        <el-form-item label="员工类型" prop="type">
          <el-select v-model="temp4.type" class="filter-item" style='width: 100%;' @change='changeEmployeeType'>
            <el-option v-for="item in employeeTypeOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        	<!-- 基础 -->
        	<el-form-item label="入职日期" prop="userEnterDay">
		   		<el-date-picker v-model="temp4.userEnterDay" type="date" placeholder="选择日期" style='width: 100%;' value-format="yyyy-MM-dd">
    			</el-date-picker>
		    </el-form-item>
		    <el-form-item label="离职日期" prop="userLeaveDay">
		   		<el-date-picker v-model="temp4.userLeaveDay" type="date" placeholder="选择日期" style='width: 100%;' value-format="yyyy-MM-dd">
    			</el-date-picker>
		    </el-form-item>
		    <el-form-item label="在职考勤（小时）" prop="hour_workTime" v-if='temp4.type == 2'>
		   		<el-input v-model="temp4.hour_workTime" />
		    </el-form-item>
		    <el-form-item label="在职天数" prop="day_workTime" v-if='temp4.type == 3'>
		   		<el-input v-model="temp4.day_workTime" />
		    </el-form-item>
		     <el-form-item label="满勤天数" prop="month_workFullTime" v-if='temp4.type == 4'>
		   		<el-input v-model="temp4.month_workFullTime" />
		    </el-form-item>
		    <el-form-item label="身份证号" prop="userIdCard">
		   		<el-input v-model="temp4.userIdCard" />
		    </el-form-item>
		    <el-form-item label="通过劳务公司" prop="recomdCompany">
		   		<el-input v-model="temp4.recomdCompany" />
		    </el-form-item>
		    <el-form-item label="劳务公司对接人" prop="recomdName">
		   		<el-input v-model="temp4.recomdName" />
		    </el-form-item>
		    <el-form-item label="对接人电话" prop="recomdPhone">
		   		<el-input v-model="temp4.recomdPhone" />
		    </el-form-item>
		    <!-- 高返费 -->
		    <el-form-item label="返费要求天数" prop="high_returnDay" v-if='temp4.type == 1'>
		   		<el-input v-model="temp4.high_returnDay" />
		    </el-form-item>
		    <el-form-item label="返费金额" prop="high_returnMoney" v-if='temp4.type == 1'>
		   		<el-input v-model="temp4.high_returnMoney" />
		    </el-form-item>
		    <el-form-item label="返出金额" prop="high_reflectFeeMoney" v-if='temp4.type == 1'>
		   		<el-input v-model="temp4.high_reflectFeeMoney" />
		    </el-form-item>
            <el-form-item label="代理费" prop="high_agentMoney" v-if='temp4.type == 1'>
                <el-input v-model="temp4.high_agentMoney" />
            </el-form-item>
            <el-form-item label="渠道联系人" prop="high_channelName" v-if='temp4.type == 1'>
               <el-input v-model="temp4.high_channelName" />
            </el-form-item>
            <el-form-item label="渠道联系人电话" prop="high_channelPhone" v-if='temp4.type == 1'>
               <el-input v-model="temp4.high_channelPhone" />
            </el-form-item>
            <el-form-item label="政策" prop="high_policy" v-if='temp4.type == 1'>
               <el-input :autosize="{ minRows: 4}" type="textarea" v-model="temp4.high_policy"/>
            </el-form-item>
		    <!-- 小时工 -->
		    <el-form-item label="合同价/时" prop="hour_cHourPrice" v-if='temp4.type == 2'>
		   		<el-input v-model="temp4.hour_cHourPrice" />
		    </el-form-item>
		    <el-form-item label="员工价/时" prop="hour_sHourPrice" v-if='temp4.type == 2'>
		   		<el-input v-model="temp4.hour_sHourPrice" />
		    </el-form-item>
            <el-form-item label="代理费/时" prop="hour_agentMoney" v-if='temp4.type == 2'>
              <el-input v-model="temp4.hour_agentMoney" />
            </el-form-item>
            <el-form-item label="渠道联系人" prop="hour_channelName" v-if='temp4.type == 2'>
              <el-input v-model="temp4.hour_channelName" />
            </el-form-item>
            <el-form-item label="渠道联系人电话" prop="hour_channelPhone" v-if='temp4.type == 2'>
              <el-input v-model="temp4.hour_channelPhone" />
            </el-form-item>
		    <el-form-item label="利润" prop="hour_profitMoney" v-if='temp4.type == 2'>
		   		<el-input v-model="hour_profitMoney" disabled/>
		    </el-form-item>
		    <!-- 日结 -->
            <el-form-item label="是否结算" prop="day_isGet" v-if='temp4.type == 3'>
              <el-select v-model="temp4.day_isGet" class="filter-item" style='width: 100%;' @change='changeIsGetOptions'>
                  <el-option v-for="item in isGetOptions" :key="item.key" :label="item.label" :value="item.key" />
              </el-select>
            </el-form-item>
            <el-form-item label="合同价/天" prop="day_cHourPrice" v-if='temp4.type == 3'>
              <el-input v-model="temp4.day_cHourPrice" />
            </el-form-item>
            <el-form-item label="员工价/天" prop="day_sHourPrice" v-if='temp4.type == 3'>
              <el-input v-model="temp4.day_sHourPrice" />
            </el-form-item>
            <el-form-item label="代理费/时" prop="day_agentMoney" v-if='temp4.type == 3'>
              <el-input v-model="temp4.day_agentMoney" />
            </el-form-item>
            <el-form-item label="渠道联系人" prop="day_channelName" v-if='temp4.type == 3'>
              <el-input v-model="temp4.day_channelName" />
            </el-form-item>
            <el-form-item label="渠道联系人电话" prop="day_channelPhone" v-if='temp4.type == 3'>
              <el-input v-model="temp4.day_channelPhone" />
            </el-form-item>
		    <el-form-item label="利润" prop="day_profitMoney" v-if='temp4.type == 3'>
		   		<el-input v-model="day_profitMoney" disabled/>
		    </el-form-item>
		    <!-- 月结 -->
		    <el-form-item label="管理费" prop="month_manageMoney" v-if='temp4.type == 4'>
		   		<el-input v-model="temp4.month_manageMoney" />
		    </el-form-item>
		    <el-form-item label="代理费" prop="month_agentMoney" v-if='temp4.type == 4'>
		   		<el-input v-model="temp4.month_agentMoney" />
		    </el-form-item>
		    <el-form-item label="员工返费" prop="month_returnMoney" v-if='temp4.type == 4'>
		   		<el-input v-model="temp4.month_returnMoney" />
		    </el-form-item>
            <el-form-item label="渠道联系人" prop="month_channelName" v-if='temp4.type == 4'>
              <el-input v-model="temp4.month_channelName" />
            </el-form-item>
            <el-form-item label="渠道联系人电话" prop="month_channelPhone" v-if='temp4.type == 4'>
              <el-input v-model="temp4.month_channelPhone" />
            </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible4 = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="userDataInput">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  <el-dialog :visible.sync="innerVisible5" title="导出数据" append-to-body width="30%">
      <el-form ref="dataForm2" label-position="right" label-width="100px">
          <el-form-item label="选择导出类型">
              <el-select filterable v-model="temp5.userType" style="width: 200px" class="filter-item">
                  <el-option v-for="item in userTypes" :key="item.key" :label="item.name" :value="item.type" />
              </el-select>
          </el-form-item>
          <el-form-item label="入职日期">
              <el-date-picker v-model="temp5.userEnterDay"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                              type="date"
                              placeholder="入职日期">
              </el-date-picker>
          </el-form-item>
          <!--<el-form-item label="在职公司">-->
              <!--<el-input v-model="temp5.companyName" style="width: 200px" />-->
          <!--</el-form-item>-->
          <!--<el-form-item label="在职天数">-->
              <!--<el-input v-model="temp5.userInDay" style="width: 200px" />-->
          <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible5 = false">{{ $t('table.cancel') }}</el-button>
          <el-button type="primary" @click="exportUserList">{{ $t('table.confirm') }}</el-button>
      </div>
  </el-dialog>
  </div>
</template>

	<script>
import { fetchUserListAjax, distributeShop, distributeShopConfirm, distributeFactory, rddUserSettlementDetail, rddUserSettlementInput} from "@/api/userList";
import { fetchShopList } from "@/api/shop";
import { fetchEnterPriseListAjax } from "@/api/enterprise";
import waves from "@/directive/waves"; // Waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import permission from "@/directive/permission/index.js"; // 权限判断指令

export default {
	name: "ComplexTable",
	components: { Pagination },
	directives: { waves, permission },
	filters: {},

	data() {
		return {
			tableKey: 0,
			list: [],
			total: 0,
			listLoading: true,
			sortOptions: [
				{ label: "已注册", key: "0" },
				{ label: "未注册", key: "1" }
			],
			listQuery: {
				pageNum: 1,
				pageSize: 20,
				isReg: '',
				userNickName: '',
				userName: '',
				userPhone: '',
			},
			temp: {
				user_id: null,
				store_id: null
			},
			temp2: {
				user_id: null
			},
			temp3: {
				user_id: null,
				company_id: null
			},
            temp5: {
                userType: null,
                userEnterDay: null,
                userInDay: null,
                companyName: null
            },
            userTypes: [{
			    type:1,
                name:'高返费'
            },{
                type:2,
                name:'小时工'
            },{
                type:3,
                name:'日结'
            },{
                type:4,
                name:'月结'
            }],
			stores: [],
			enterpriseOptions: [],
			downloadLoading: false,
			innerVisible: false,
			innerVisible2: false,
			innerVisible3: false,
			innerVisible4: false,
			innerVisible5: false,
			temp4: {
				type: "1",
			},
			employeeTypeOptions: [
				{ label: "高返费", key: 1 },
				{ label: "小时工", key: 2 },
				{ label: "日结", key: 3 },
				{ label: "月结", key: 4 },
			],
            isGetOptions: [
			    { label: "是", key: 1 },
                { label: "否", key: 0 }
            ],
			rules: {
				type: [
					{
						required: true,
						message: "必填",
						trigger: "change"
					}
				],
				userEnterDay: [
					{
						required: true,
						message: "必填",
						trigger: "change",
					}
				],
				hour_workTime: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				day_workTime: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				month_workFullTime: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				userIdCard: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				recomdCompany: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				recomdName: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				recomdPhone: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
                high_channelName: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
                high_channelPhone: [
                    {
                        required: true,
                        message: "必填",
                        trigger: "blur"
                    }
                ],
				hour_cHourPrice: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				hour_sHourPrice: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				month_manageMoney: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				],
				month_returnMoney: [
					{
						required: true,
						message: "必填",
						trigger: "blur"
					}
				]
			},
		};
	},
	created() {
		this.getList();
		this.getStoreOptions();
		this.getEnterPriseOptions();
	},
	methods: {
		getEnterPriseOptions() {
			try {
				fetchEnterPriseListAjax().then(result => {
					result.data.data.forEach(item => {
						this.enterpriseOptions.push({
							key: item.id,
							value: item.companyName
						});
					});
				});
			} catch (err) {
				console.log(err);
			}
		},
		getStoreOptions() {
			try {
				fetchShopList().then(result => {
					result.data.data.forEach(item => {
						this.stores.push({
							key: item.id,
							value: item.storeName
						});
					});
				});
			} catch (err) {
				console.log(err);
			}
		},
		distributeShop() {
			distributeShop(this.temp).then(response => {
				this.innerVisible = false;
				this.getList();
			});
		},
		distributeFactory() {
			distributeFactory(this.temp3).then(response => {
				this.innerVisible3 = false;
				this.getList();
			});
		},
		distributeShopConfirm() {
			distributeShopConfirm(this.temp2).then(response => {
				this.innerVisible2 = false;
				this.getList();
			});
		},
		handleDistributeConfirm(row) {
			this.innerVisible2 = true;
			this.temp2.user_id = row.id;
		},
		handleDistribute(row) {
			this.innerVisible = true;
			this.temp.user_id = row.id;
		},
		handleDistributeFactory(row) {
			this.innerVisible3 = true;
			this.temp3.user_id = row.id;
			this.temp3.company_id = null;
		},
		async getList() {
			this.listLoading = true;
			try {
				const result = await fetchUserListAjax(this.listQuery);
				if (result.data.code === 0) {
					this.list = result.data.data.pageData;
					this.total = result.data.data.maxCount;
				}
				this.listLoading = false;
			} catch (err) {
				console.log(err);
				this.listLoading = false;
			}
		},

		handleFilter() {
			this.listQuery.pageNum = 1;
			this.getList();
		},

		formatSex(row) {
			return row.userSex == 1 ? "男" : "女";
		},

		formatStatus(row) {
			if (row.rdd_user_statuses.length > 0) {
				const arr = ["待分配", "待入职", "待确认", "在职", "离职"];
				return arr[row.rdd_user_statuses[0].userStatus];
			}
			return '-'
		},
        exportUserList() {
            let userTypeStr = ''
            if(this.temp5.userType!==null){
                userTypeStr = 'type='+this.temp5.userType+'&&';
            }
            let userInDayStr = ''
            if(this.temp5.userInDay!==null){
                userInDayStr = 'userInDay='+this.temp5.userInDay+'&&';
            }
            let userEnterDayStr = ''
            if(this.temp5.userEnterDay!==null){
                userEnterDayStr = 'userEnterDay='+this.temp5.userEnterDay+'&&';
            }
            let companyNameStr = ''
            if(this.temp5.companyName!==null){
                companyNameStr = 'companyName='+this.temp5.companyName+'&&';
            }
            let baseUrl
            if(window.location.href.indexOf('admin.renduoduow.com')>0){
                baseUrl = 'http://api.renduoduow.com'
            } else if(window.location.href.indexOf('a.renduoduow.com')>0){
                baseUrl = 'http://dev.renduoduow.com'
            }
            let url = baseUrl + '/admin/rddUserSettlementExport?'+userTypeStr+userInDayStr+userEnterDayStr+companyNameStr
            if(url.lastIndexOf('&&')!=-1){
                url=url.substring(0, url.lastIndexOf('&&'));
            }
            let urlList = url.split('?')
            if(urlList[1]==''){
                url = urlList[0]
            }
            window.open(url)
            this.innerVisible5 = false
		},

        handleDownload() {
            this.innerVisible5 = true
        },

		formatJson(filterVal, jsonData) {
			return jsonData.map(v =>
				filterVal.map(j => {
					if (j === "registrationTime") {
						return parseTime(v[j]);
					} else if (j === "userSex") {
						return v[j] === "0" ? "女" : "男";
					} else if (j === "disabled") {
						return v[j] === "0" ? "有效" : "无效";
					} else {
						return v[j];
					}
				})
			);
		},

		async handleUserDataInput(data) {
			const res = await rddUserSettlementDetail(data.rdd_user_statuses[0].id)
			if(res.data.code == 0 && res.data.data && res.data.data.hasOwnProperty('id')) {
				this.innerVisible4 = true;
				this.temp4 = res.data.data;
			} else {
				this.innerVisible4 = true;
				this.temp4 = {
					type: 1,
					user_status_id: data.rdd_user_statuses[0].id,
				};
			}
			this.$nextTick(() => {
				this.$refs["dataForm4"].clearValidate();
			});
		},

		changeEmployeeType(data) {
			this.$refs["dataForm4"].clearValidate();
			var userStatusId = this.temp4.user_status_id;
			var id = this.temp4.id;
			this.temp4 = {
				type: data,
				user_status_id: userStatusId
			};
			if(id) {
				this.temp4.id = id;
			}
		},
        changeIsGetOptions(data) {
            this.temp4.day_isGet = data
        },
		async userDataInput() {
			this.$refs["dataForm4"].validate(valid => {
				if (valid) {
					this.userDataInputAjax();
				}
			});

		},

		async userDataInputAjax() {
			if(this.temp4.type == 2) {
				this.temp4.hour_profitMoney = this.hour_profitMoney;
			} else if(this.temp4.type == 3) {
				this.temp4.day_profitMoney = this.day_profitMoney;
			}
			const req = await rddUserSettlementInput(this.temp4);
			this.innerVisible4 = false;
		}
	},

	computed: {
		hour_profitMoney() {
			return (this.temp4.hour_cHourPrice - this.temp4.hour_sHourPrice - this.temp4.hour_agentMoney) || 0
		},

		day_profitMoney() {
			return this.temp4.day_workTime *  (this.temp4.day_cHourPrice - this.temp4.day_sHourPrice -this.temp4.day_agentMoney )|| 0
		}
	}
};
</script>
